package com.nvshen.zhangmeiying.utils;

import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by wxc on 14-7-8.
 */
public abstract class PerfectAsyncHandler extends AsyncHttpResponseHandler
{
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
    {
        onFinish();
        super.onSuccess(statusCode, headers, responseBody);
        NetDialogUtils.dissmissProgressDialog();
        if (responseBody != null)
        {
            try
            {
                JSONObject json = new JSONObject(new String(responseBody));
                if (json.getInt("err") == 200)
                {
                    try
                    {
                        onGetSuccess(headers, json.getString("data"));
                    }
                    catch (JSONException e)
                    {
                        onGetSuccess(headers, "");
                    }
                }
                else
                {
                    onGetFailure(json.toString());
                }
            }
            catch (JSONException e)
            {
                onGetFailure("服务器内部错误");
                e.printStackTrace();
            }
        }
        else
        {
            onGetFailure("服务器内部错误");
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
    {
        onFinish();
        super.onFailure(statusCode, headers, responseBody, error);
        NetDialogUtils.dissmissProgressDialog();
        if (responseBody == null)
        {
            onGetFailure(new String(""));
        }
        else
        {
            onGetFailure(new String(responseBody));
        }
    }

    /**
     * Fired when a request returns successfully, override to handle in your own
     * code
     */
    public abstract void onGetSuccess(Header[] header, String result);

    /**
     * Fired when a request fails to complete, override to handle in your own
     * code
     */
    public abstract void onGetFailure(String errorCause);

    public void onFinish()
    {

    }
}
